package aiui

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/httplib"
	"math/rand"
	"strconv"
	"time"
	"tools"
)

var (
	upload_url  = "https://openapi.xfyun.cn/v2/aiui/entity/upload-resource"
	check_url   = "https://openapi.xfyun.cn/v2/aiui/entity/check-resource"
	appid       = "5acc14bd";
	x_namespace = "RCWLKJ"
	accountkey  = "13b07d14aad44663853053df8b6760a0"
)

// @title 上传动态实体
// @param resName 资源名称
// @param data 上传数据    {"字段名称":"字段内容"}
func UploadEntity(resName string, data, dim map[string]string) (string, error) {
	rand.Seed(time.Now().UnixNano())
	nonce := strconv.Itoa(rand.Int())
	curTime := strconv.Itoa(int(time.Now().Unix()))
	checkSum := tools.MD5Encode(accountkey + nonce + curTime)

	bytes, err := json.Marshal(data)
	if err != nil {
		return "", err
	}

	dimBytes, err := json.Marshal(dim)
	if err != nil {
		return "", err
	}

	type dataStruct struct {
		Sid  string `json:"sid"`
		Csid string `json:"csid"`
	}

	type result struct {
		Code string     `json:"code"`
		Desc string     `json:"desc"`
		Sid  string     `json:"sid"`
		Data dataStruct `json:"data"`
	}

	res := &result{}

	err = httplib.Post(upload_url).
		Header("X-NameSpace", x_namespace).
		Header("X-Nonce", nonce).
		Header("X-CurTime", curTime).
		Header("X-CheckSum", checkSum).
		Param("appid", appid).
		Param("res_name", fmt.Sprintf("%s.%s", x_namespace, resName)).
		Param("pers_param", string(dimBytes)).
		Param("data", base64.StdEncoding.EncodeToString(bytes)).ToJSON(res)

	if err != nil {
		return "", err
	}

	return res.Data.Sid, err
}

func CheckEntity(sid string) bool {

	rand.Seed(time.Now().UnixNano())
	nonce := strconv.Itoa(rand.Int())
	curTime := strconv.Itoa(int(time.Now().Unix()))
	checkSum := tools.MD5Encode(accountkey + nonce + curTime)

	type dataStruct struct {
		Sid   string `json:"sid"`
		Csid  string `json:"csid"`
		Error int64  `json:"error"`
		Reply string `json:"reply"`
	}

	type result struct {
		Code string     `json:"code"`
		Desc string     `json:"desc"`
		Sid  string     `json:"sid"`
		Data dataStruct `json:"data"`
	}

	res := &result{}

	err := httplib.Post(check_url).
		Header("X-NameSpace", x_namespace).
		Header("X-Nonce", nonce).
		Header("X-CurTime", curTime).
		Header("X-CheckSum", checkSum).
		Param("sid", sid).ToJSON(res)

	if err != nil {
		return false
	}

	if res.Code == "00000" {
		return true
	}

	return false
}